<script setup>
  import { ref } from 'vue'
  import { useUserStore } from '@/stores'
  import { login } from '@/api/user'
  const loginPopup = ref(null)
  const userStore = useUserStore()
  function open() {
    loginPopup.value.open()
  }
  function close() {
    loginPopup.value.close()
  }
  defineExpose({ open })
  const formData = ref({
    username: '',
    password: ''
  })
  function handleLogin() {
    let form = formData.value
    if (!form.username || !form.password) {
      ElMessage.error('请输入用户名和密码')
      return
    }
    login(form)
      .then(res => {
        userStore.setToken(res.data.token)
        ElMessage.success('登录成功')
      })
      .catch(err => {
        ElMessage.error('用户名或密码错误')
      })
      .finally(() => {
        close()
      })
  }
</script>

<template>
  <popup ref="loginPopup">
    <div class="login">
      <div class="close" @click="close">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-quxiao"></use>
        </svg>
      </div>
      <div class="title">登录</div>
      <div class="input flex-center">
        <input v-model="formData.username" placeholder="请输入用户名" />
      </div>
      <div class="input flex-center">
        <input
          type="password"
          v-model="formData.password"
          placeholder="请输入密码"
        />
      </div>
      <div class="button" @click="handleLogin">登录</div>
    </div>
  </popup>
</template>

<style lang="scss" scoped>
  .login {
    position: relative;
    background-color: var(--color-background);
    border-radius: 16px;
    width: 350px;
    display: flex;
    align-items: center;
    flex-direction: column;
    padding: 48px 25px;
    .close {
      position: absolute;
      right: 20px;
      top: 20px;
      cursor: pointer;
    }
    .title {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 24px;
    }
    .input {
      width: 100%;
      height: 48px;
      background: var(--color-active-background);
      color: var(--color-primary-label);
      margin: 10px;
      border-radius: 999px;
      input {
        width: 100%;
        font-size: 16px;
        flex: 1;
        height: 100%;
        padding: 0 16px;
        background: initial;
        caret-color: red;
        border-radius: 999px;
      }
    }
    .button {
      width: 100%;
      height: 48px;
      line-height: 48px;
    }
  }
  @media screen and (max-width: 320px) {
    .login {
      width: max-content;
    }
  }
</style>
